package com.company.BinarySortTree;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}15:57
 */
public class Demo {
    public static void main(String[] args) {
        int[] arr = {7,3,10,12,5,1,9};
        BinaryTree binaryTree = new BinaryTree();
        for (int i = 0; i < arr.length; i++){
            Node node = new Node(arr[i]);
            binaryTree.add(node);
        }
        binaryTree.infixOrder();
    }

    static class BinaryTree{
        private Node root;
        public void add(Node node){
            if (root == null){
                root = node;
            }else {
                root.add(node);
            }
        }
        //中序遍历
        public void infixOrder(){
            if (root == null){
                System.out.println("树为空");
            }else {
                root.infixOrder();
            }
        }
    }

    static class Node{
        int value;
        Node left;
        Node right;

        public Node(int value) {
            this.value = value;
        }

        //添加节点方法
        //递归的形式添加节点，注意需要满足二叉排序树的要求
        public void add(Node node){
            if (node == null){
                return;
            }

            //判断传入的节点的值，和当前树的根节点的值的关系
            if (node.value < this.value) {
                if (this.left == null) {
                    this.left = node;
                } else {
                    this.left.add(node);
                }
            }else {
                if (this.right == null){
                    this.right = node;
                }else {
                    this.right.add(node);
                }
            }
        }
        public void infixOrder(){
            if (this.left!=null){
                this.left.infixOrder();
            }
            System.out.println(this);
            if (this.right!=null){
                this.right.infixOrder();
            }
        }

        @Override
        public String toString() {
            return "Node{" +
                    "value=" + value +
                    '}';
        }
    }

}
